package com.example.seh.person.post;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.seh.R;
import com.example.seh.constant.Constant;
import com.example.seh.square.Post;
import com.example.seh.square.simple.DefaultUseWithServerActivity;
import com.example.seh.util.UserMsg;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyPostActivity extends AppCompatActivity {
    private ListView lvPost;
    private List<Post> users = new ArrayList<>();
    private MyPostAdapter myPostAdapter;
    private SmartRefreshLayout smartRefreshLayout;
    private LinearLayout layout;
    private int currentNum = 1;
    private boolean isRefresh = true;

    private Handler myHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    myPostAdapter.notifyDataSetChanged();
                    if (!isRefresh){
                        smartRefreshLayout.finishLoadMore();
                    }
                    break;

            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_post);

        lvPost = findViewById(R.id.my_post);
        layout = findViewById(R.id.is_post);
        smartRefreshLayout = findViewById(R.id.srl);
        smartRefreshLayout.setEnableRefresh(false);


        getData();
        setItemListener();




    }

    private void setItemListener() {

        /**
         * 单击帖子跳转
         */

        lvPost.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(MyPostActivity.this, DefaultUseWithServerActivity.class);

                Post post = users.get(position);
                int postId = post.getPostId();
                intent.putExtra("postId", postId);
                startActivity(intent);

            }
        });


        /**
         * 长按删除帖子
         */
        lvPost.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                AlertDialog.Builder builder=new AlertDialog.Builder(MyPostActivity.this);

                builder.setMessage("删除后就没了，确定删除帖子吗？");

                builder.setTitle("提示");
                //添加AlertDialog.Builder对象的setPositiveButton()方法
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //删除当前item数据
                        int postId = users.remove(position).getPostId();

                        Toast.makeText(MyPostActivity.this, "已删除该帖子", Toast.LENGTH_SHORT).show();

                        OkHttpClient okHttpClient = new OkHttpClient();

                        Request request = new Request.Builder()
                                .get()
                                .url(Constant.POST_DELETE + postId)
                                .build();
                        Call call = okHttpClient.newCall(request);
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                Log.e("okhttp", "删除数据失败");
                                e.printStackTrace();
                            }
                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                Log.e("okhttp","删除成功");
                            }
                        });

                        Message message = new Message();
                        message.what = 1;
                        myHandler.sendMessage(message);

                        show();

                    }
                })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                return true;
            }
        });
    }

    private void getData() {
        setData();
        setListener();
        myPostAdapter = new MyPostAdapter(
                this,
                users,
                R.layout.my_post_item
        );
        lvPost.setAdapter(myPostAdapter);

    }

    private void setListener() {
        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isRefresh = false;
                currentNum++;
                setData();
            }
        });
    }

    private void setData() {

        OkHttpClient okHttpClient = new OkHttpClient();

        Request request = new Request.Builder()
                .get()
                .url(Constant.MY_POST+"userId="+ UserMsg.userDTO.getUserId() +"&pageIndex="+currentNum)
                .build();
        Log.e("地址：", request.url().toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp", "获取数据失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String squareData = response.body().string();
                Log.e("数据：", squareData);
                getDataFromJsonData(squareData);

            }


        });
    }

    private void getDataFromJsonData(String studyData) {
        try {
            JSONObject jsonObject = new JSONObject(studyData);
            String PlanDataStr = jsonObject.getString("data");

            if (!PlanDataStr.equals("[]")) {
                Gson gson = new Gson();
                Type type = new TypeToken<List<Post>>() {
                }.getType();
                List<Post> list = gson.fromJson(PlanDataStr, type);
                Log.e("list", list.toString());
                users.addAll(list);
            }else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MyPostActivity.this,"数据加载完了哦~",Toast.LENGTH_SHORT).show();
                    }
                });
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Message message = new Message();
        message.what = 1;
        myHandler.sendMessage(message);

        show();
    }

    private void show(){
        if (users.isEmpty()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    layout.setVisibility(View.VISIBLE);
                }
            });
        }else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    layout.setVisibility(View.GONE);
                }
            });
        }
    }
}